<!--订单结算页-->
<template>
  <div class="checkorder">
    <div class="container checkorder-frame">
      <div class="order-frame col-12 col-sm-12 col-md-8">
        <div class="label-frame nostyle">
          <span>Select delivery address and confirm your order</span>
          <div class="btn-frame" @click="clickCutAddress">New Address</div>
        </div>
        <div class="express-frame">
          <Loading style="padding: 0" v-if="addressLoading" />
          <div
            v-else
            class="express-panel"
            v-for="(item, exindex) in addressList"
            :key="exindex"
            :style="
              exindex == selectAddress
                ? 'border:1px solid #F9644E'
                : 'border:1px solid #eee'
            "
            @click="clickAddress(exindex)"
          >
            <van-checkbox
              :value="exindex == selectAddress"
              icon-size="0.8rem"
            ></van-checkbox>
            <div class="express-fast">
              <p class="address" style="font-size: 0.7rem">
                {{ item.recipient_name }}
                <span
                  v-if="item.telephone"
                  style="font-size: 0.6rem; color: #656466; margin-left: 0.5rem"
                  >{{ item.telephone }}</span
                >
              </p>
              <p class="address" style="margin-top: 0.2rem">
                <span>{{ item.address }}&nbsp;</span>
                <span>{{ item.city_name }}&nbsp;</span>
                <span>{{ item.state_name }}&nbsp;</span>
                <span>{{ item.country_name }}&nbsp;</span>
                <span>{{ item.postal_code }}</span>
              </p>
            </div>
            <div class="icon-panel ac-bg" @click.stop="clickEdit(exindex)">
              <svg
                class="icon"
                style="width: 0.8rem; height: 0.8rem"
                aria-hidden="true"
              >
                <use xlink:href="#edit"></use>
              </svg>
            </div>
          </div>
          <p
            v-if="addressList.length == 0 && !addressLoading"
            class="express-nodata"
            @click="clickCutAddress"
          >
            Receiving Address? <span class="address-btn">New address</span>
          </p>
        </div>
        <div class="label-frame">
          <span style="color: #323233">Logistics information</span>
          <span></span>
        </div>
        <div class="express-frame">
          <Loading style="padding: 0" v-if="expressLoading" />
          <div
            v-else
            class="express-panel"
            v-for="(item, exindex) in expressList"
            :key="exindex"
            :style="
              exindex == selectExpress
                ? 'border:1px solid #F9644E'
                : 'border:1px solid #eee'
            "
            @click="clickExpress(exindex)"
          >
            <van-checkbox
              :value="exindex == selectExpress"
              icon-size="0.8rem"
            ></van-checkbox>
            <div class="express-fast">
              <p class="address" style="font-size: 0.7rem">
                {{ item.name }}
                <span
                  v-if="item.description"
                  style="font-size: 0.6rem; color: #656466"
                  >({{ item.description }})</span
                >
              </p>
              <p class="address" style="margin-top: 0.2rem">
                <span>$ {{ item.logistics_price }}</span>
              </p>
            </div>
          </div>
          <p
            v-if="expressList.length == 0 && !expressLoading"
            class="express-nodata"
          >
            Currently, there is no logistics option
          </p>
        </div>
        <div class="label-frame">
          <span>Order product</span>
          <span style="color: #000">
            {{ produList.length }}model and {{ produTotal }} pieces in
            total</span
          >
        </div>
        <div
          class="product-frame"
          v-for="(item, index) in produList"
          :key="index"
        >
          <div class="product-img">
            <van-image class="img" fit="cover" lazy-load :src="item.pic" />
          </div>
          <div class="product-panel">
            <div class="product-fast">
              <p class="product-title">
                {{ item.title }}
              </p>
              <p class="product-type">
                {{ item.attribute_me }}
              </p>
            </div>

            <p class="product-price">
              <span class="price">${{ item.price }}</span>
              <span class="number">x{{ item.number }}</span>
            </p>
          </div>
        </div>
      </div>
      <div
        class="pay-frame col-12 col-sm-12 col-md-4"
        :style="isMobile ? 'margin-top: 2rem;' : ''"
      >
        <div class="pay-panel">
          <div class="title">
            <span>Order Summary</span>
            <div class="vips-frame" v-if="userInfo.grade">
              <img class="grade-img" src="@/assets/imgs/img1.png" />
              <span class="grade">{{ userInfo.grade.weight }}</span>
            </div>
          </div>
          <div class="price-frame">
            <div class="price-panel">
              <span>Product Price</span>
              <span style="font-family: 'BTBlack'">${{ produTotalPrice }}</span>
            </div>
            <div class="price-panel">
              <span>Shipping Cost</span>
              <span style="font-family: 'BTBlack'">${{ freigt }}</span>
            </div>
            <div class="price-panel total">
              <span style="font-size: 0.8rem">Subtotal</span>
              <span style="font-size: 1rem; font-family: 'BTBlack'"
                >${{ produTotalPrice + freigt }}</span
              >
            </div>
          </div>
          <div class="discount-frame">
            <div class="discount-panel" v-if="userInfo.grade">
              <span class="label"
                >Member discount ({{ parseInt(userInfo.grade.equity) }}%)</span
              >
              <span>- {{ reduction.equity }} USD</span>
            </div>
            <div class="discount-panel">
              <span class="label">Birthday remission</span>
              <span>- {{ reduction.derate }} USD</span>
            </div>
            <div class="discount-panel">
              <span class="label"
                >Point deduction({{ parseFloat(userInfo.point) }})</span
              >
              <span>- {{ reduction.point }} USD</span>
            </div>
          </div>
          <div class="price-frame" style="width: 80%">
            <div class="price-panel total">
              <span style="font-size: 0.8rem">Discount Price</span>
              <span style="font-size: 1rem; font-family: 'BTBlack'"
                >${{ discount_price }}</span
              >
            </div>
          </div>
          <div class="pay-btn ac-bg bg" @click="clickPay">PAY NOW</div>
          <div class="payment-frame">
            <div class="payment-panel">
              <van-checkbox :value="1" icon-size="0.8rem"></van-checkbox>
              <img src="@/assets/imgs/paypal.jpg" />
            </div>
          </div>
        </div>
        <img class="img" src="@/assets/imgs/paymethods.png" />
        <nuxt-link to="/other/deliorder/paymethod" class="alink"
          >Payment Method</nuxt-link
        >
      </div>
    </div>
  </div>
</template>
<script>
import tool from "@/common/tool.js";
export default {
  data() {
    return {
      produList: [], //商品列表
      produTotal: 0, //商品总件数
      produTotalPrice: 0, //商品价格
      freigt: 0, //运费
      addressLoading: false, //地址加载
      expressLoading: false, //物流加载
      selectExpress: 0, //选择的物流渠道
      selectPay: 0, //选择的支付渠道
      selectAddress: 0, //选择的地址
      expressList: [], //物流列表
      reduction: {
        //减免金额数
        equity: 0, //会员等级折扣比例
        derate: 0, //会员生日减免金额
        point: 0, //积分减免金额
      },
      //折扣价结算时的价钱
      discount_price: 0,
      userInfo: {
        id: "",
        nick_name: "--",
        grade: {
          weight: 0,
          equity: 0, //会员等级折扣比例
          derate: 0, //会员生日减免金额
        },
        experience: 0,
        point: 0, //积分
      },
    };
  },
  activated() {
    if (this.refreshPro) {
      this.intData();
    }
    this.getAddress();
  },
  mounted() {
    try {
      this.tips.closeToast();
    } catch (error) {}
  },
  computed: {
    addressList() {
      return this.$store.state.user.addressList;
    },
    checkOrderAddress() {
      return this.$store.state.user.checkOrderAddress;
    },
    refreshPro() {
      return this.$store.state.order.refreshPro;
    },
  },
  methods: {
    //编辑地址
    clickEdit(index) {
      let addressInfo = this.addressList[index];
      tool.setStorageAsyn("addressInfo", addressInfo, () => {
        this.$router.push({
          path: "/user/address/editaddress",
          query: {
            type: "edit",
          },
        });
      });
    },
    //获取用户信息
    async getUserInfo() {
      let res = await this.$store.dispatch("user/userInfo");
      let userInfo = {};
      if (res.code == 0 && res.data) {
        userInfo = res.data;
        this.userInfo = userInfo;
        this.sumDidscount(userInfo);
      }
    },
    //切换地址
    clickCutAddress() {
      this.$router.push({
        path: "/user/address/editaddress",
        query: {
          type: "select",
        },
      });
    },
    //结算单初始化
    async intData() {
      this.tips.startLoadingToast();
      this.expressLoading = true;
      let cartCheckList = tool.getStorage("cartCheckList"); //获取结算商品列表
      console.log();
      this.produList = cartCheckList;
      let produTotal = 0;
      let expressList = []; //物流渠道
      for (let i = 0; i < cartCheckList.length; i++) {
        produTotal += cartCheckList[i].number;
      }
      this.produTotal = produTotal;
      let res = await this.$store.dispatch("order/orderPreset", {
        product_array: cartCheckList,
      });
      this.expressLoading = false;
      this.tips.closeToast();
      if (res.code == 0 && res.data != undefined) {
        expressList = res.data.logistics;
        this.expressList = expressList;
        if (expressList.length > 0) {
          //有可选物流
          this.freigt = parseFloat(expressList[0].logistics_price);
        }
        this.produTotalPrice = parseFloat(res.data.total_price);
        if (this.isLogin) {
          this.getUserInfo();
        } else {
          this.discount_price = this.produTotalPrice + this.freigt;
        }
      }
      this.$store.commit("order/setRefreshPro", false); //停止刷新结算单
    },
    //获取地址
    async getAddress() {
      if (this.isLogin) {
        this.addressLoading = true;
        await this.$store.dispatch("user/address");
        this.addressLoading = false;
      } else {
        let cartList = tool.getStorage("addressList");
        if (cartList) {
          this.$store.commit("user/setAddressList", cartList);
        }
      }
    },
    //选择地址
    clickAddress(index) {
      this.selectAddress = index;
    },
    //计算折扣
    sumDidscount(userInfo) {
      let pro_price = parseFloat(this.produTotalPrice);
      let total_price =
        parseFloat(this.produTotalPrice) + parseFloat(this.freigt);
      let equity = parseInt(userInfo.grade.equity);
      let derate = parseFloat(userInfo.grade.derate);
      let point = parseFloat(userInfo.point);
      console.log(point);
      this.reduction.equity = (pro_price * equity) / 100;
      if (tool.getLocalTimeryymmhh() == this.userInfo.birth_date) {
        this.reduction.derate = derate;
      }
      this.reduction.point = pro_price > point ? point : pro_price;
      let redu =
        this.reduction.equity + this.reduction.derate + this.reduction.point;
      let discount_price = total_price - redu;
      if (discount_price < 0) {
        this.discount_price = 0;
      } else {
        this.discount_price = parseFloat(discount_price.toFixed(2));
      }
    },
    //切换物流
    clickExpress(index) {
      this.selectExpress = index;
      this.freigt = parseFloat(this.expressList[index].logistics_price);
      this.sumDidscount(this.userInfo);
    },
    //支付
    async clickPay() {
      if (this.addressList.length == 0) {
        this.$toast("Please add logistics information first");
      } else {
        this.tips.startLoadingToast();
        let res = {};
        if (this.isLogin) {
          let form = {
            product_array: this.produList,
            shipping_address_id: "",
            logistics_id: "",
            pay_channel: "10",
          };
          if (this.expressList.length != 0) {
            form.logistics_id =
              this.expressList[this.selectExpress].logistics_id;
          }
          if (this.addressList.length != 0) {
            form.shipping_address_id = this.addressList[this.selectAddress].id;
          }
          res = await this.$store.dispatch("order/orderCreate", form);
        } else {
          let form = {
            product_array: this.produList,
            shipping_address_params: this.addressList[this.selectAddress],
            logistics_id: "",
            pay_channel: "10",
          };
          if (this.expressList.length != 0) {
            form.logistics_id =
              this.expressList[this.selectExpress].logistics_id;
          }
          console.log(form);
          res = await this.$store.dispatch("order/orderCreateNl", form);
        }
        this.tips.closeToast();
        if (res.code == 0 && res.data != undefined) {
          if (res.data.length == 0) {
            this.$router.push("/user/order");
          } else {
            this.$store.commit("menu/setCartRefresh", true); //刷新购物车
            this.$store.commit("menu/setCartList", []); //清空购物车
            tool.setStorageAsyn("payConfirmId", res.data.order_id, () => {});
            location.href = res.data.pay_url;
          }
        } else {
          this.$toast.fail(res.msg);
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
body {
  background: #fff !important;
}
@import "order.less";
</style>